<template>
  <el-card shadow="never" style="border: none">
    <div slot="header">
      <i class="el-icon-ticket" />
      <span>巡查内容</span>
    </div>

    <div class="flex">
      <div v-if="tabs.length > 0" class="index-tabs">
        <el-tabs v-model="activeTab" tab-position="left" @tab-click="changeTab">
          <el-tab-pane v-for="tab in tabs" :key="tab.targetId" :name="tab.targetName">
            <div slot="label">
              <span v-if="getTodoNum(tab.targetName) === 0">{{ tab.targetName }}</span>
              <el-badge v-else class="badge" :value="getTodoNum(tab.targetName)" :max="99">{{ tab.targetName }}</el-badge>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="index-list">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['sys:task:add']"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row>

        <index-list
          :loading="loading"
          :list="indexMap[activeTab] || []"
          @update="handleUpdate"
          @refresh="getList"
        />
      </div>
    </div>

    <security-dialog
      :visible="open"
      :title="title"
      :init-data="indexInfo"
      :target-name="activeTab"
      :target-opts="targetOpts"
      :key-opts="keyOpts"
      :task-id="taskId"
      @cancel="open = false"
      @submit="submitForm"
    />
  </el-card>
</template>
<script>
import IndexList from './IndexList'
import SecurityDialog from './SecurityDialog'
import { listTaskDetailItem, addTaskDetailItem, updateTaskDetailItem } from '@/api/task/task'
import { uploadFiles } from '@/api/system/file'
import { listElementAll } from '@/api/job/element'

export default {
  name: 'IndexCard',
  components: { IndexList, SecurityDialog },
  dicts: ['sys_file_business_type'],
  data() {
    return {
      loading: true,
      indexList: [],
      indexMap: {}, // 根据指标名称分类
      activeTab: '',
      tabs: [],
      taskId: null,
      // 是否显示弹出层
      open: false,
      title: '',
      indexInfo: undefined,
      targetOpts: [], // 核查指标
      keyOpts: [] // 核查要点
    }
  },
  created() {
    this.taskId = this.$route.params.taskId
    this.getList()
    this.getElementList()
  },
  methods: {
    getList() {
      this.loading = true
      const params = {
        taskId: this.taskId,
        pageNo: 1,
        pageSize: 1000
      }
      listTaskDetailItem(params).then(res => {
        this.indexList = res.data.sort(function(a, b) {
          return a.showSort - b.showSort
        })
        this.loading = false
        this.initData()
      })
    },
    initData() {
      const indexMap = {}; const tabs = []
      this.indexList.forEach(item => {
        if (!indexMap[item.targetName]) {
          tabs.push({ targetName: item.targetName, targetId: item.targetId })
        }
        indexMap[item.targetName] = indexMap[item.targetName] || []
        indexMap[item.targetName].push({
          ...item,
          fileList: item.fileList.map(v => ({
            ...v,
            isImage: /\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/.test(v.url)
          })).sort((a, b) => `${a.isImage}` > `${b.isImage}` ? -1 : 1)
        })
      })

      this.indexMap = indexMap
      this.tabs = tabs
      this.activeTab = this.activeTab || (tabs.length > 0 ? tabs[0].targetName : '')
    },
    getTodoNum(targetName) {
      const list = this.indexMap[targetName]
      return list.filter(item => item.result !== 0 && !item.result).length
    },
    getElementList() {
      const params = {
        type: this.$route.params.type
      }
      listElementAll(params).then(res => {
        for (const x of res.data) {
          if (x.type === 0) {
            this.targetOpts.push({ value: x.id, label: x.name })
          }
          if (x.type === 1) {
            this.keyOpts.push({ value: x.id, label: x.name })
          }
        }
      })
    },
    changeTab(tab) {
      this.activeTab = tab.name
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.indexInfo = undefined
      this.open = true
      this.title = '添加核查细项'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.indexInfo = { ...row }
      this.open = true
      this.title = '修改核查细项'
    },
    /** 提交按钮 */
    submitForm: async function(formData) {
      if (formData.id) {
        const files = formData.fileList.filter(item => !!item.raw).map(item => item.raw)
        if (files.length > 0) {
          const type = this.$route.params.type
          let busiType = 0
          Object.entries(this.dict.label.sys_file_business_type).forEach(item => {
            if (item[1] === { environment: '环保任务', safe: '安全任务' }[type]) {
              busiType = item[0]
            }
          })
          const fd = new FormData()
          fd.append('connectId', formData.id)
          fd.append('busiType', busiType)
          files.forEach(file => {
            fd.append('files', file)
          })
          await uploadFiles(fd)
        }
        updateTaskDetailItem(formData).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        })
      } else {
        addTaskDetailItem(formData).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.index-tabs {
  flex-shrink: 0;
}
.index-list {
  width: 0;
  flex-grow: 2;
}
::v-deep .badge sup {
  top: 10px;
}
</style>
